package com.icesoft.system.auth.realm;

import com.icesoft.system.auth.entity.AuthToken;
import com.icesoft.system.auth.entity.LoginUser;
import com.icesoft.system.entity.Account;
import com.icesoft.system.entity.BaseLoginUser;
import com.icesoft.system.service.impl.AccountServiceImpl;
import com.icesoft.system.service.impl.PermissionServiceImpl;
import com.icesoft.system.service.impl.UserServiceImpl;
import lombok.RequiredArgsConstructor;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.Set;

@Component
@RequiredArgsConstructor
public class AuthRealm extends AuthorizingRealm {

	private final AccountServiceImpl accountService;

	private final UserServiceImpl userService;

	private final PermissionServiceImpl permissionService;

	@Override
	public boolean supports(AuthenticationToken token) {
		return token instanceof AuthToken;
	}

	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
		LoginUser<?> loginUser = (LoginUser<?>) principalCollection.getPrimaryPrincipal();
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		info.setRoles(loginUser.getRoles());
		info.setStringPermissions(loginUser.getPermissions());
		return info;
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
		AuthToken jwtToken = (AuthToken) authenticationToken;
		String token = jwtToken.getToken();
		Account account = jwtToken.getLoginUser().getAccount();
		BaseLoginUser user = jwtToken.getLoginUser().getUser();
		if (user == null) {
			throw new AuthenticationException("用户不存在");
		}
		Set<String> roleNames = jwtToken.getLoginUser().getRoles();
		if (roleNames == null) {
			roleNames = new HashSet<>();
		}
		Set<String> permission = jwtToken.getLoginUser().getPermissions();
		if (permission == null) {
			permission = new HashSet<>();
		}
		LoginUser<?> loginUser = new LoginUser<>(account, user, roleNames, permission);
		return new SimpleAuthenticationInfo(loginUser, account.getAuthSecret(), getName());
	}
}
